package org.mybatis.jpetstore.web.actions;

import cn.webwheel.WebContext;
import cn.webwheel.WebContextAware;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

abstract class AbstractActionBean implements Serializable, WebContextAware {

    private static final long serialVersionUID = -1767714708233127983L;

    protected static final String ERROR = "/WEB-INF/jsp/common/Error.html";

    protected void setMessage(String value) {
        List<String> messages = (List<String>) ctx.getRequest().getAttribute("messages");
        if (messages == null) {
            ctx.getRequest().setAttribute("messages", messages = new ArrayList<String>());
        }
        messages.add(value);
    }

    public List<String> getMessages() {
        return (List<String>) ctx.getRequest().getAttribute("messages");
    }

    protected transient WebContext ctx;

    public Map<String, Object> getSessionScope() {
        HttpSession session = ctx.getRequest().getSession();
        Enumeration enm = session.getAttributeNames();
        Map<String, Object> map = new HashMap<String, Object>();
        while (enm.hasMoreElements()) {
            String k = (String) enm.nextElement();
            map.put(k, session.getAttribute(k));
        }
        return map;
    }

    @Override
    public void setWebContext(WebContext ctx) {
        this.ctx = ctx;
    }

    public String fmt(Object o, String s) {
        if (o == null) return null;
        if (o instanceof Number) {
            return new DecimalFormat(s).format(o);
        }
        return new SimpleDateFormat(s).format(o);
    }

    public String param(String k) {
        return ctx.getRequest().getParameter(k);
    }
}
